<?php
/**
 * Created by PhpStorm.
 * userValidate: hms
 * Date: 2018/8/7
 * Time: 9:27
 */

namespace app\firm\controller;

use think\Controller;
use think\Config;
use think\Db;
use redis\Redis;
use think\Request;
use think\Session;
use app\firm\model\ProjectUser;
use app\firm\model\ProjectBank;
use app\firm\model\Notice;
use app\firm\model\Config as Confv;
use app\firm\validate\bankValidate;
use expand\Yunst;
use expand\YunPay;

class Index extends Common
{
    
    
    /*
     * 安全设置首页
     * @param Request $request
     * @param ProjectBank $projectBankqueren 
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function index(Request $request , ProjectBank $projectBank) {
        $user_info = $request->firm_info;
        $where['pjtuser_id'] = ['eq',$user_info['id']];
        $res = $projectBank->selectBankInfo($where,'id');
        $result = Config::get('code.success');
        $result['isPayPwd'] = empty($user_info['pay_password'])?'NO':'YES';
        $result['is_sign'] = $user_info['is_sign'];
        return json($result);
    }
    
    /*
     * 安全设置首页
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function qianYue(Request $request) {
        $user_info = $request->firm_info;
        $YunClass = new Yunst();
        $url = $YunClass->QiYeQianYue($user_info['bizUserId']);
        $result = Config::get('code.success');
        $result['url'] = $url;
        return json($result);
    }
    
    /*
     * 银行卡列表
     * @param Request $request
     * @param ProjectBank $projectBankqueren 
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function cardList(Request $request , ProjectBank $projectBank) {
        $user_info = $request->firm_info;
        $where['pjtuser_id'] = ['eq',$user_info['id']];
        $where['status'] = ['eq','YES'];
        $res = $projectBank->selectBankInfo($where);
        foreach ($res as $k => $val) {
            $prefix = substr($val['bank_num'],0,4);
            $suffix = substr($val['bank_num'],-4,4);
            $maskBankCardNo = $prefix." **** **** **** ".$suffix;
            $res[$k]['bank_num'] = $maskBankCardNo;
            unset($val['trance_num']);
        }
        $result = Config::get('code.success');
        $result['data'] = $res;
        return json($result);
    }
    
    /**
     * 修改登录密码
     * @param Request $request
     * @param \app\firm\model\ProjectUser $projectUser
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function savePassword(Request $request , ProjectUser $projectUser , Notice $notice)
    {
        $param = $request->param();
        $redis = Redis::instance();
        $user_info = $request->firm_info;
        if ($param['password'] && $param['old_password']) {
            $password = sha1(md5($param['old_password'] . $user_info['salt']));
            if ($password == $user_info['password']) {
                $salt = generateRandomString(4);
                $new_password = sha1(md5($param['password'] . $salt));
                if ($projectUser->save(['password' => $new_password , 'salt' => $salt] , ['id' => $user_info['id']])) {
                    Db::startTrans();
                    try {
                        $data = [
                            'uid' => $user_info['id'],
                            'title' => '密码',
                            'content' => '您好,企业家,您的登录密码已修改成功.如有疑问,欢迎致电400-605-9006',
                            'type' => 2
                        ];
                        $notice->save($data);
                        $token = $redis->get('user:' . $user_info['id']);
                        $user_info['salt'] = $salt;
                        $user_info['password'] = $new_password;
                        $redis->hSet('firm_info' , $token , json_encode($user_info));
                        Db::commit();
                        $result = Config::get('code.success');
                    } catch (\Exception $e) {
                        Db::rollback();
                        return $e->getMessage();
                    }
                } else {
                    $result = Config::get('code.error');
                }
            } else {
                $result = Config::get('code.pwdError');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }
    
    /**
     * 发送支付验证码
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function sendPayCode(Request $request) {
        $user_info = $request->firm_info;
        $res = redisCode($user_info['mobile'],'pay_code_');
        if($res){
            $row = SmsToSend($user_info['mobile'],$res);
            if($row['code'] == 0){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
                $result['msg'] = $row['msg'];
            }
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }
    
    /**
     * 设置支付密码
     * @param Request $request
     * @param ProjectUser $projectUser
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function setPayPwd(Request $request, ProjectUser $projectUser, Notice $notice) {
        $redis = Redis::instance();
        $param = $request->param();
        $user_info = $request->firm_info;
        $code = $redis->get('pay_code_' . $user_info['mobile']);
        if(!empty($user_info['pay_password'])){
            return $result = Config::get('code.isBeing');
        }
        if($code === $param['code']){
            $salt = generateRandomString(4);
            $payPassword = sha1(md5($param['pay_password'] . $salt));
            if ($projectUser->save(['pay_password' => $payPassword, 'pay_salt' => $salt], ['id' => $user_info['id']])) {
                Db::startTrans();
                try {
                    $data = [
                        'uid' => $user_info['id'],
                        'title' => '密码',
                        'content' => '您好,企业家,您的支付密码已设置成功.如有疑问,欢迎致电400-605-9006',
                        'type' => 2
                    ];
                    $notice->save($data);
                    $token = $redis->get('user:' . $user_info['id']);
                    $user_info['pay_password'] = $payPassword;
                    $user_info['pay_salt'] = $salt;
                    $redis->hSet('firm_info', $token, json_encode($user_info));
                    Db::commit();
                    $result = Config::get('code.success');
                } catch (\Exception $e) {
                    Db::rollback();
                    return $e->getMessage();
                }
            } else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.codeFail');
        }
        return json($result);
    }
    
    /**
     * 修改支付密码
     * @param Request $request
     * @param ProjectUser $projectUser
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function savePayPwd(Request $request, ProjectUser $projectUser, Notice $notice) {
        $param = $request->param();
        $redis = Redis::instance();
        $user_info = $request->firm_info;
        $code = $redis->get('pay_code_' . $user_info['mobile']);
        if ($code === $param['code']) {
            if ($param['newPayPwd'] && $param['oldPayPwd']) {
                $password = sha1(md5($param['oldPayPwd'] . $user_info['pay_salt']));
                if ($password == $user_info['pay_password']) {
                    $salt = generateRandomString(4);
                    $new_password = sha1(md5($param['newPayPwd'] . $salt));
                    if ($projectUser->save(['pay_password' => $new_password, 'pay_salt' => $salt], ['id' => $user_info['id']])) {
                        Db::startTrans();
                        try {
                            $data = [
                                'uid' => $user_info['id'],
                                'title' => '密码',
                                'content' => '您好,企业家,您的支付密码已修改成功.如有疑问,欢迎致电400-605-9006',
                                'type' => 2
                            ];
                            $notice->save($data);
                            $token = $redis->get('user:' . $user_info['id']);
                            $user_info['pay_salt'] = $salt;
                            $user_info['pay_password'] = $new_password;
                            $redis->hSet('firm_info', $token, json_encode($user_info));
                            Db::commit();
                            $result = Config::get('code.success');
                        } catch (\Exception $e) {
                            Db::rollback();
                            return $e->getMessage();
                        }
                    } else {
                        $result = Config::get('code.error');
                    }
                } else {
                    $result = Config::get('code.pwdError');
                }
            } else {
                $result = Config::get('code.mistake');
            }
        } else {
            $result = Config::get('code.codeFail');
        }
        return json($result);
    }
    
    /**
     * 添加银行卡
     * @param Request $request
     * @param Yunst $YunClass
     * @param ProjectBank $projectBank
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function addBankCard(Request $request, ProjectBank $projectBank, Yunst $YunClass) {
        $param = $request->param();
        $user_info = $request->firm_info;
        $validate = new bankValidate();
        $where['pjtuser_id'] = ['eq',$user_info['id']];
        $where['status'] = ['eq','YES'];
        $where['type'] = ['eq','person'];
        $bankInfo = $projectBank->getBankInfo($where, 'status');
        if($bankInfo['status'] == 'YES'){
            return json(Config::get('code.bankCardLimitOne'));
        }
        if ($validate->check($param)) {
            $res = $YunClass->bindCard($user_info['bizUserId'], $param['bank_num'], $param['bank_mobile'], $user_info['legal_person'], $user_info['legal_person_id_card']);
            file_put_contents(date("Y-m-d H", time()) . 'addCard.txt', $res . PHP_EOL, FILE_APPEND);
        } else {
            $result['status'] = 203;
            $result['msg'] = $validate->getError();
            return json($result);
        }
        if ($res['status'] == 'OK') {
            $signedValue = json_decode($res['signedValue'], true);
            $param['pjtuser_id'] = $user_info['id'];
            $param['trance_num'] = $signedValue['tranceNum']; //流水号
            $param['trans_date'] = $signedValue['transDate'] ? $signedValue['transDate'] : date('Ymd'); //申请时间
            $param['bank_name'] = $signedValue['bankName']; //银行名称
            $param['bank_code'] = $signedValue['bankCode']; //银行代码
            $param['card_type'] = $signedValue['cardType']; //类型
            $param['type'] = 'person';
            $param['true_name'] = $user_info['legal_person'];
            if($projectBank->save($param)){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        } else {
            $res['status'] = 203;
            $result['msg'] = $res['message'];
        }
        return json($result);
    }
    
    /**
     * 确认绑定银行卡
     * @param Request $request
     * @param Yunst $YunClass
     * @param ProjectBank $projectBank
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function confirmBankCard(Request $request, ProjectBank $projectBank, Yunst $YunClass) {
        $param = $request->param();
        $user_info = $request->firm_info;
        $where['pjtuser_id'] = ['eq',$user_info['id']];
        $where['type'] = ['eq','person'];
        $where['status'] = ['eq','NO'];
        $bankInfo = $projectBank->getLastBankInfo($where,$filed='*',$order='id desc');
        if (empty($bankInfo)) {
            return json(Config::get('code.bindBankError'));
        }
        $bankInfo['tranceNum'] = $bankInfo['trance_num'];
        $bankInfo['transDate'] = $bankInfo['trans_date'];
        $res = $YunClass->ActbindCard($user_info['bizUserId'], $bankInfo, $param['code']);
        file_put_contents('confirmBankCard.txt', $res . PHP_EOL, FILE_APPEND);
        if ($res['status'] == 'OK') {
            if($projectBank->save(['status'  => 'YES'],['pjtuser_id' => $user_info['id']])){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        } else {
            $res['status'] = 201;
            $result['msg'] = $res['message'];
        }
        return json($result);
    }
    
    /**
     * 消息通知列表
     * @param Request $request
     * @param Notice $notice
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function noticeList(Request $request, Notice $notice) {
        $user_info = $request->firm_info;
        $param = $request->param();
        $pageNumber = $param['pageNumber'] ? $param['pageNumber'] : 1;
        $pageSize = $param['pageSize'] ? $param['pageSize'] : 10;
        $limit = ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $where['uid'] = ['eq',$user_info['id']];
        $where['type'] = ['eq',2];
        $res = $notice->selectLimitInfo($where,$limit);
        $total = $notice->selectInfo($where,'id');
        $where['isread'] = ['eq',0];
        $row = $notice->selectInfo($where,'id');
        $result = Config::get('code.success');
        $result['data'] = $res;
        $result['total'] = count($total);
        $result['num'] = count($row);
        return json($result);
    }
    
    /**
     * 读取消息
     * @param Request $request
     * @param Notice $notice
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function readNotice(Request $request, Notice $notice) {
        $user_info = $request->firm_info;
        $param = $request->param();
        $res = $notice->save(['isread'=>1],['id'=>$param['id'],'uid'=>$user_info['id'],'type'=>2]);
        $result = empty($res)?Config::get('code.error'):Config::get('code.success');
        return json($result);
    }
    
    /**
     * 获取底部信息
     * @param Request $request
     * @param Notice $notice
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function getFootInfo(Request $request, Confv $confv) {
        $result = Config::get('code.success');
        $result['weixin_code'] = $confv->confv('weixin_code');
        $result['weixin_code2'] = $confv->confv('weixin_code2');
        $result['tel'] = $confv->confv('tel');
        $result['kefuemail'] = $confv->confv('kefuemail');
        $result['wokertime'] = $confv->confv('wokertime');
        $result['address'] = $confv->confv('address');
        $result['copyright'] = $confv->confv('copyright');
        $result['weixin'] = $confv->confv('weixin');
        $result['sina'] = $confv->confv('sina');
        return json($result);
    }


    /**
     * 获取银行卡信息
     * @param Request $request
     * @return \think\response\Json
     * @author hey_heyang(1442435897@qq.com)
     */
    public function getBankCardInfo(Request $request){
        $param = $request->param();
        $yun = new Yunst();
        if(empty($param['cardNo'])){
            $result = Config::get('code.error');
            $result['msg'] = '未获取到银行卡号';
        }else{
            $res=$yun->getCardInfo(trim($param['cardNo']));
            if($res['status']=='OK'){
                $signedValue = json_decode($res['signedValue'], true);
                $result = Config::get('code.success');
                $result['data'] =$signedValue['cardBinInfo'] ;
            }else{
                $result = Config::get('code.error');
                $result['msg'] = $res['message'];
            }
        }
        return json($result);
    }

    /**
     * modify 测试
     * @param Request $request
     * @param Notice $notice
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function modify(Request $request) {
        $user_info = $request->firm_info;
        $data['modify'] = true;
        $redis->hSet('firm_info', $user_info['token'], json_encode($data));
        return json($result);
    }

}